from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from . import  models
import json
from django.core.paginator import Paginator
# Create your views here.
def index(request):
    return HttpResponse("welcome to django")


def html_index(request):
    # title="个人博客"
    #categories=models.Category.objects.all()#查询所有分类名称
    articles=models.Article.objects.all()#查询所有文章
    #locals就是取函数里面的局部变量，放到一个字典里面
    page=request.GET.get("page",1)
    limit=request.GET.get("limit",5)
    paginator=Paginator(articles,limit)
    articles=paginator.page(page)
    data={"articles":articles}
    return render(request,'index.html',data)


def category_article(request):
    #categories = models.Category.objects.all()  # 查询所有分类名称
    category_id=request.GET.get("id")
    category=models.Category.objects.get(id=category_id)
    articles=models.Article.objects.filter(category_id=category_id)
    return render(request,'category.html',locals())


def article(request,id):
    article=models.Article.objects.get(id=id)
    categories = models.Category.objects.all()  # 查询所有分类名称
    return render(request,'detail.html',locals())
#http://127.0.0.1:8000/tqz

def add_article(request):
    if request.method == "GET":
        return render(request,'add_article.html')
    else:
        title = request.POST.get("title")
        tag = request.POST.get("tag")
        desc = request.POST.get("desc")
        content = request.POST.get("content")
        category_id = request.POST.get("category")
        art = models.Article(title=title,tag=tag,desc=desc,
                       content=content,category_id=category_id)
        art.save()
        return HttpResponseRedirect('/index')



def request_test(request):
    print(request.method) #请求方式
    print(request.GET.get("get")) # url?name=xiaohei
    print(request.POST.get("post")) # body里面传的
    print(request.COOKIES.get("sessionid")) #获取cookies里面的
    print(request.META.get("HTTP_META")) #获取header里面的,如果要获取header字段名变成
    print(request.path_info) #获取请求的路径
    print(request.FILES.get("file_name")) #获取文件
    print(json.loads(request.body))#入参是json的

    return HttpResponse("OK")


from user import forms
def register(request):
    if request.method == "GET":
        return render(request,'register.html')
    else:
        form = forms.UserForm(request.POST)
        if form.is_valid():
            models.User.objects.create(**form.cleaned_data)
            data = {"code": 0, "msg": "注册成功"}
            return JsonResponse(data)
        return JsonResponse(form.errors.get_json_data())